﻿using System;
using System.Collections.Generic;

namespace NetSurveillance.WebApp.Foundations
{
    public abstract class PersistentDataContainer
    {
        protected virtual IDictionary<string, object> DataStore { get; private set; }

        public static Func<PersistentDataContainer> LoadCurrent { get; set; }

        public static Func<PersistentDataContainer> LoadCurrentCache { get; set; }

        public static Func<PersistentDataContainer> LoadCurrentApplication { get; set; } 

        public static PersistentDataContainer Current
        {
            get
            {
                return LoadCurrent == null ? null : LoadCurrent();
            }
        }

        public static PersistentDataContainer CurrentCache
        {
            get { return LoadCurrentCache == null ? null : LoadCurrentCache(); }
        }

        public static PersistentDataContainer CurrentApplication
        {
            get { return LoadCurrentApplication == null ? null : LoadCurrentApplication(); }
        }

        protected PersistentDataContainer()
        {
            DataStore = RecoveryStore();
            if (DataStore != null) return;
            DataStore = new Dictionary<string, object>();
            PersistentStore(DataStore);
        }

        protected abstract IDictionary<string, object> RecoveryStore();

        protected abstract void PersistentStore(IDictionary<string, object> store);

        public virtual T Read<T>(string keyName)
        {
            if (DataStore.Keys.Contains(keyName))
                return (T)DataStore[keyName];
            return default(T);
        }

        public virtual T Read<T>()
        {
            return Read<T>(typeof(T).Name);
        }

        public virtual void Add<T>(string key, T value)
        {
            DataStore[key] = value;
        }

        public virtual void Add<T>(T value)
        {
            Add(typeof(T).Name, value);
        }

        public virtual void Remove(string keyName)
        {
            DataStore.Remove(keyName);
        }

        public virtual void Remove<T>()
        {
            Remove(typeof (T).Name);
        }

        public virtual void Clear()
        {
            DataStore.Clear();
        }
    }
}